﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml;
using System.Diagnostics;
using System.Globalization;
using System.ComponentModel;
using Microsoft.Win32;
using System.IO;
using System.Windows.Controls.Primitives;

namespace Минуточка
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class wMain : Window
    {
        bool _loaded = false;
        System.Windows.Forms.NotifyIcon nicon = new System.Windows.Forms.NotifyIcon();
        ContextMenu cmenu = new ContextMenu();
        public static string _file = System.IO.Path.Combine(
            System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().FullName),
            "Events.xml");

        XmlDocument eventsXML = new XmlDocument();
        

        public wMain()
        {
            InitializeComponent();
            nicon.Text = "Минуточка";
            nicon.Visible = true;
            nicon.MouseClick += new System.Windows.Forms.MouseEventHandler(nicon_MouseClick);
            nicon.Icon = new System.Drawing.Icon(Application.GetResourceStream(new Uri("icon.ico",UriKind.Relative)).Stream);

            cmenu.Items.Add(new MenuItem() { Header = "Показать" });
            cmenu.Items.Add(new Separator());
            cmenu.Items.Add(new MenuItem() { Header = "Выйти из программы" });

            (cmenu.Items[0] as MenuItem).Click += (s, e) => { this.WindowState = WindowState.Normal; this.Activate(); };
            (cmenu.Items[2] as MenuItem).Click += (s, e) => { this.Close(); };

            //InputBinding ib = new InputBinding(ApplicationCommands.Save,
            //new KeyGesture(Key.Enter, ModifierKeys.Control));
            //this.InputBindings.Add(ib);
            //// Bind handler
            //CommandBinding cb = new CommandBinding(ApplicationCommands.Save);
            //cb.Executed += (s, e) => { CommitEventEdit(); };
            //this.CommandBindings.Add(cb);

        }

       

        void nicon_MouseClick(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Right)
            {
                ContextMenuService.SetPlacement(cmenu, System.Windows.Controls.Primitives.PlacementMode.MousePoint);
                cmenu.IsOpen = true;
            }
            else
            {
                this.WindowState = WindowState.Normal;
                this.Activate();
            }
            
        }

        private void TextBlock_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            this.DragMove();
            Properties.Settings.Default.Position = this.RestoreBounds;
            Properties.Settings.Default.Save();
        }

        private void BtnExit_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try {
                Rect pos = Properties.Settings.Default.Position;
                this.Top = pos.Top;
                this.Left = pos.Left;
                this.Width = pos.Width;
                this.Topmost = Properties.Settings.Default.Topmost;
                this.sldOpacity.Value = Properties.Settings.Default.Opacity;
            }
            catch { }

             RegistryKey runkey = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run",true);
        if (runkey == null || runkey.GetValue("Минуточка") == null || runkey.GetValue("Минуточка").ToString() == "" )
            mnuAutoRun.IsChecked = false;
        else
            mnuAutoRun.IsChecked = true;

            this.Activate();
            
            LoadAndShowEvents();
            
            _loaded = true;
        }

        void LoadAndShowEvents()
        {
            if (System.IO.File.Exists(_file))
                eventsXML.Load(_file);
            else
                eventsXML.LoadXml("<Events><Event Date=\"21.12.2012 0:00:00\" Format=\"ДД дней HH:mm:ss\" Color=\"#FF00FFFF\" EventNotify=\"0\" Sound=\"\">До конца света осталось</Event></Events>");
            lstEvents.Items.Clear();
            foreach (XmlNode node in eventsXML.SelectNodes("Events/Event"))
            {
                Event ev = new Event(node);
                lstEvents.Items.Add(ev);
                ev.ToTray += new ToTray(event_ToTray);
            }
        }

        void event_ToTray(Event sender)
        {
            nicon.BalloonTipIcon = System.Windows.Forms.ToolTipIcon.Warning;
            nicon.BalloonTipTitle = "Время вышло!";
            nicon.BalloonTipText = sender.Descr;
            nicon.ShowBalloonTip(5);
        }

        private void lstEvents_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.RemovedItems.Count > 0)
            {
                Event ev = (e.RemovedItems[0] as Event);
                if (ev != null)
                {
                    if (ev != null) ev.CancelEdit();
                    lstEvents.Items.Refresh();
                    lstEvents.AllowDrop = true;
                }
            }
            
        }

        private void lstEvents_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            BeginEventEdit();
        }

        private void btnEditCommit_Click(object sender, RoutedEventArgs e)
        {
            CommitEventEdit();
        }

        private void btnRemove_Click(object sender, RoutedEventArgs e)
        {
            RemoveEvent();

        }

        private void BtnMinimize_Click(object sender, RoutedEventArgs e)
        {
            this.WindowState = WindowState.Minimized;
        }

        private void mnuNew_Click(object sender, RoutedEventArgs e)
        {
            NewEvent();
        }

        private void sldOpacity_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (_loaded)
            {
                Properties.Settings.Default.Opacity = ((Slider)sender).Value;
                Properties.Settings.Default.Save(); 
            }
        }


        private void mnuAbout_Click(object sender, RoutedEventArgs e)
        {
            string about = "Программа \"Минуточка\"\n\rАвтор: Alexey for7Raid\n\rE-mail: alexey@for7raid.ru";
            MessageBox.Show(about, "Минутка - О программе", MessageBoxButton.OK, MessageBoxImage.Information);
        }

        private void lstEvents_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {

                Event moving = (Event)GetBoundItemFromPoint(lstEvents, e.GetPosition(lstEvents));
                if (moving != null && lstEvents.AllowDrop && e.LeftButton == MouseButtonState.Pressed && e.ClickCount == 1)
                    DragDrop.DoDragDrop(lstEvents, moving, DragDropEffects.Move | DragDropEffects.Scroll); 
        }

        private void lstEvents_Drop(object sender, DragEventArgs e)
        {
            Event moved = (Event)e.Data.GetData(typeof(Event));
            Event after = (Event)GetBoundItemFromPoint(lstEvents, e.GetPosition(lstEvents));

            if (moved!=after)
            {
                moved.Source.ParentNode.InsertBefore(moved.Source,after.Source);

                eventsXML.Save(_file);

                lstEvents.Items.Remove(moved);
                lstEvents.Items.Insert(lstEvents.Items.IndexOf(after), moved);
            }


        }

        private object GetBoundItemFromPoint(ListBox box, Point point)
        {
            UIElement element = box.InputHitTest(point) as UIElement;
            while (element != null)
            {
                if (element == box)
                {
                    return null;
                }
                object item = box.ItemContainerGenerator.ItemFromContainer(element);
                bool itemFound = !object.ReferenceEquals(item, DependencyProperty.UnsetValue);
                if (itemFound)
                {
                    return item;
                }
                else
                {
                    element = VisualTreeHelper.GetParent(element) as UIElement;
                }
            }
            return null;
        }

        private void lstEvents_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter && e.KeyboardDevice.Modifiers == ModifierKeys.Control)
                CommitEventEdit();
            else if (e.Key == Key.Enter)
                BeginEventEdit();
            else if (e.Key == Key.Delete)
                RemoveEvent();
            else if (e.Key == Key.Escape)
                CancelEventEdit();
            else if (e.Key == Key.Insert)
                NewEvent();
            else if (e.Key == Key.C && e.KeyboardDevice.Modifiers == ModifierKeys.Control)
                CopySelectedEvent();
        }

        private void NewEvent()
        {
            XmlNode node = eventsXML.CreateElement("Event");
            node.Attributes.Append(eventsXML.CreateAttribute("Date"));
            node.Attributes.Append(eventsXML.CreateAttribute("Format"));
            node.Attributes.Append(eventsXML.CreateAttribute("Color"));
            node.Attributes.Append(eventsXML.CreateAttribute("EventNotify"));
            node.Attributes.Append(eventsXML.CreateAttribute("Sound"));
            node.InnerText = "";
            node.Attributes["Date"].Value = DateTime.Now.ToString("dd.MM.yyyy HH:mm");
            node.Attributes["Format"].Value = "чч:mm:ss";
            node.Attributes["Color"].Value = "#FF00FFFF";
            node.Attributes["EventNotify"].Value = "0";

            eventsXML.DocumentElement.AppendChild(node);

            Event ev = new Event(node);
            lstEvents.Items.Add(ev);
            ev.BeginEdit();
            lstEvents.SelectedItem = ev;
            ev.ToTray+=new ToTray(event_ToTray);
            lstEvents.AllowDrop = false;
        }

        void BeginEventEdit()
        {
            if (lstEvents.SelectedItem != null)
            {
                ((Event)lstEvents.SelectedItem).BeginEdit();
                lstEvents.AllowDrop = false;
            }
        }

        void CancelEventEdit()
        {
            if (lstEvents.SelectedItems.Count > 0)
            {
                Event ev = (lstEvents.SelectedItem as Event);
                if (ev != null) ev.CancelEdit();
                lstEvents.Items.Refresh();
                lstEvents.AllowDrop = true;
            }
        }

        void CommitEventEdit()
        {
            if (lstEvents.SelectedItems.Count > 0)
            {
                Event ev = (lstEvents.SelectedItem as Event);
                if (ev != null)
                {
                    ev.Commit();
                    lstEvents.Items.Refresh();
                    lstEvents.AllowDrop = true;
                }
            }
        }

        void RemoveEvent()
        {

            if (lstEvents.SelectedItem != null)
            {
                Event ev = ((Event)lstEvents.SelectedItem);
                eventsXML.DocumentElement.RemoveChild(ev.Source);
                lstEvents.Items.Remove(ev);
                eventsXML.Save(_file);
                ev.ToTray -= event_ToTray;
                ev.Dispose();
            }  
            
        }

        bool _isWiden = false;
        private void window_initialeWiden(object sender, MouseButtonEventArgs e)
        {
            _isWiden = true;
        }

        private void window_endWiden(object sender, MouseButtonEventArgs e)
        {
            _isWiden = false;
            ((Rectangle)sender).ReleaseMouseCapture();
            Properties.Settings.Default.Position = this.RestoreBounds;
            Properties.Settings.Default.Save();
        }

        private void window_Widen(object sender, MouseEventArgs e)
        {
            if ( _isWiden)
            {
                Rectangle rect = sender as Rectangle;
                rect.CaptureMouse();
                this.Width = e.GetPosition(this).X + 5;
            }
            
        }


        private void mnuAutoRun_Click(object sender, RoutedEventArgs e)
        {
            RegistryKey runkey = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true);
            if (mnuAutoRun.IsChecked)
                runkey.SetValue("Минуточка",System.Reflection.Assembly.GetExecutingAssembly().Location);
            else
                runkey.DeleteValue("Минуточка");
        }

        private void mnuTopmost_Click(object sender, RoutedEventArgs e)
        {
                Properties.Settings.Default.Topmost = ((MenuItem)sender).IsChecked;
                Properties.Settings.Default.Save();
        }

        private void mnuHelp_Click(object sender, RoutedEventArgs e)
        {
            Stream file = Application.GetResourceStream(new Uri("help.txt",UriKind.Relative)).Stream;
            byte[] text = new byte[file.Length];
            file.Read(text, 0, (int)file.Length);
            MessageBox.Show(Encoding.UTF8.GetString(text));
        }

        private void btnCalendar_Click(object sender, RoutedEventArgs e)
        {
            Event ev = ((Event)lstEvents.SelectedItem);
            wCalendar wc = new wCalendar();
            wc.Datemask = ev.Date;
            if (wc.ShowDialog()==true)
            {
                ev.Date = wc.Datemask;
            }
        }

        private void chkEvent_Click(object sender, RoutedEventArgs e)
        {
            if (e.OriginalSource is CheckBox)
            {
                Event ev = ((Event)lstEvents.SelectedItem);
                CheckBox chb = (CheckBox)e.OriginalSource;
                int n = Convert.ToInt32( chb.Tag);

                if (chb.IsChecked == true)
                    ev.EventNotify |= (EventNotifyType)n;
                else
                    ev.EventNotify = (EventNotifyType)((int)ev.EventNotify-n);
                
                if (chb.IsChecked == true && n == 8)
                {
                    OpenFileDialog ofd = new OpenFileDialog();
                    ofd.Filter = "MP3 files (*.mp3)|*.mp3|WAV files (*.wav)|*.wav|All files (*.*)|*.*";
                    ofd.FilterIndex = 0;
                    ofd.CheckPathExists = true;
                    if (ofd.ShowDialog() == true)
                    {
                        ev.Sound = ofd.FileName;
                    }
                    else
                    {
                        if (!System.IO.File.Exists(ev.Sound))
                        {
                            ev.EventNotify = (EventNotifyType)((int)ev.EventNotify - 8);
                        }
                    }
                }
            }
        }

        private void mnuCopy_Click(object sender, RoutedEventArgs e)
        {
            CopySelectedEvent();
        }

        private void CopySelectedEvent()
        {
            Event ev = ((Event)lstEvents.SelectedItem);
            Clipboard.SetText(ev.ToString());
        }



    }
}
